package com.vertx.verticles;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Context;

import java.util.Date;

/**
 * @name: MyVerticle
 * @description: MyVerticle
 * @author: jiangcs
 */
public class YourVerticle extends AbstractVerticle {
    @Override
    public void start() throws Exception {
        Context context = vertx.getOrCreateContext();
        if (context.isEventLoopContext()) {
            System.out.println("Context attached to Event Loop");
        } else if (context.isWorkerContext()) {
            System.out.println("Context attached to Worker Thread");
        } else if (!Context.isOnVertxThread()) {
            System.out.println("Context not attached to a thread managed by vert.x");
        }
        context.put("userName", "vert.x");
        context.runOnContext((v) -> {
            System.out.println("This will be executed asynchronously in the same context");

            String userName = context.get("userName");
            System.out.println("userName: " + userName);
        });

        vertx.createHttpServer()
                .requestHandler(req -> {
                    System.out.println(req.path());
                    System.out.println("name is: " + config().getString("name"));

                    req.response()
                            .putHeader("Content-Type", "text/plain")
                            .end("Your: Hello World!");
                }).listen(8081);

        // 一次性执行
        long timerId = vertx.setTimer(2000, (id) -> {
            System.out.println(new Date());
            System.out.println("setTimer execute id: " + id);
        });
        System.out.println(new Date());
        System.out.println("setTimer ready id: " + timerId);

        // 周期性执行
        long periodicId = vertx.setPeriodic(5000, (id) -> {
            System.out.println(new Date());
            System.out.println("setPeriodic execute id: " + id);
        });
        System.out.println(new Date());
        System.out.println("setPeriodic ready id: " + periodicId);
    }
}
